package com.hertz.appr.pojo;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.web.util.HtmlUtils;

import com.hertz.appr.http.MyHttpClient;
import com.hertz.appr.http.MyHttpElement;
import com.hertz.appr.http.Parameter;
import com.hertz.appr.http.Response;
import com.hertz.appr.json.JSONArray;
import com.hertz.appr.json.JSONException;
import com.hertz.appr.json.JSONObject;
import com.hertz.appr.oauth.AccessToken;
import com.hertz.appr.oauth.OAuth;
import com.hertz.appr.pojo.db.Message;
import com.hertz.appr.pojo.db.Robot;
import com.hertz.appr.service.RobotGang;
import com.hertz.appr.util.Configuration;
import com.hertz.appr.util.Util;
import com.hertz.appr.util.WeiboException;

public class Mentions implements Comparable<Mentions>{
	
	private Long id;
	private String provider;
	/*
	 * twitter id ,provider's twitter id
	 */
	private String tid;
	private String nick;
	private String uid;
	private String text;
	private String reply;
	private Short type;
	private Short flag;
	private long createTime;
	private long systemTime;
	private long actionId;
	private Mentions sourceTwitter;
	
	private MyHttpClient httpClient;
	private RobotGang robotGang;
	
	private final String qq_api_mentions = "http://open.t.qq.com/api/statuses/mentions_timeline";
	private final String sina_api_mentions = "http://api.t.sina.com.cn/statuses/mentions.json";
	
	private Logger log = Logger.getLogger(Mentions.class);
	
	public Mentions(String provider){
		this.provider = provider;
	}
	public void init(){
		this.httpClient = new MyHttpClient(provider);
	}
	
	public List<Message> getMentions(Paging page) throws Exception{
		page.setProvider(provider);
		List<Message> list = new ArrayList<Message>();
		String api = "";
		if(provider == null || provider.equals("")){
			return list;
		}else if(provider.equals("qq"))
			api = qq_api_mentions;
		else if(provider.equals("sina"))
			api = sina_api_mentions;
		else 
			return list;
		OAuth oauth = robotGang.getOauth(provider,Robot.type_rw,Robot.type_r);
		if(oauth == null){
			log.info("no oauth,may be api limit");
			return null;
		}
		MyHttpElement he = oauth.getOauthHttpElement(api,MyHttpClient.GET, page.getQueryParams());
//		he.addQueryString("reqnum", String.valueOf(reqnum));
//		log.debug("queryString : " + he.getQueryString());
    	Response response = httpClient.httpRequest(api, he);
		list = constructTwitter(response);
		return list;
	}
	
	public List<Message> constructTwitter(Response res) throws Exception{
		log.debug(res.toString());
		List<Message> list = new ArrayList<Message>();
		if(res == null){
			return list;
		}
		try {
			JSONArray ja = null;
			if(provider.equals(Configuration.QQ_PROVIDER)){
				JSONObject jsonObject = res.asJSONObject();
				if(jsonObject.getString("ret") == null || !jsonObject.getString("ret").equals("0")){
					log.debug("result is error,response=" + res);
					return null;
				}
				if(jsonObject.has("data")){
					String dataStr = jsonObject.getString("data");
					if(StringUtils.isBlank(dataStr.toString()) || dataStr.equals("null")){
						log.debug("result is error,data=null");
						return null;
					}
					JSONObject data = jsonObject.getJSONObject("data");
					ja = data.getJSONArray("info");
				}
				
			}else{
				ja = res.asJSONArray();
			}
            int size = ja.length();
            list = new ArrayList<Message>(size);
           
            for (int i = 0; i < size; i++) {
                list.add(buildTwitter(ja.getJSONObject(i)));
            }
            return list;
        } catch (JSONException jsone) {
            throw new WeiboException(jsone);
        } catch (WeiboException te) {
            throw te;
        }
	}
	
	public Message buildTwitter(JSONObject jo) throws Exception{
		if(provider.equals(Configuration.QQ_PROVIDER))
			return buildTwitter4qq(jo);
		else if(provider.equals(Configuration.SINA_PROVIDER))
			return buildTwitter4sina(jo);
		else 
			return null;
	}
	
	private Message buildTwitter4qq(JSONObject jo) throws Exception{
		Message t = new Message();
		t.setProvider(provider);
		t.setTid(jo.getString("id"));
		t.setCreateTime(jo.getLong("timestamp"));
		t.setNick(jo.getString("nick"));
		t.setOrigtext(jo.getString("text"));
		t.setUid(jo.getString("name"));
		t.setType(Short.valueOf(jo.getString("type")));
		if(jo.has("source") && jo.getString("source") != null && !jo.getString("source").equals("null")){
//			log.debug("get source,string=" + jo.getString("source"));
			Message sourceT = buildTwitter(jo.getJSONObject("source"));
			t.setSourceTwitter(sourceT);
			t.setSourceTid(sourceT.getTid());
		}
		return t;
		
	}
	private Message buildTwitter4sina(JSONObject jo) throws Exception{
		Message t = new Message();
		t.setProvider(provider);
		t.setTid(jo.getString("id"));
		long date = new Date(jo.getString("created_at")).getTime();
		t.setCreateTime(date);
		String text = jo.getString("text");
		if(StringUtils.isNotBlank(text)){
			text = HtmlUtils.htmlUnescape(text);
		}
		t.setOrigtext(text);
		
		JSONObject user = jo.optJSONObject("user");
		t.setNick(user.getString("name"));
		t.setUid(user.getString("id"));
//		t.setType()
		return t;
	}
	
	@Override
	public String toString(){
		return "Message{" +
		" provider=" + String.format("%1$4S", provider) +
		", tid=" + String.format("%1$-15S", tid) +
        ", create_time='" + this.createTime + '\'' +
        ", uid=" + String.format("%1$-20S", uid) +
        ", nick=" + String.format("%1$-20S", this.nick) +
        ", type=" + String.format("%1$-3S", this.type) +
        ", flag=" + String.format("%1$-3S", this.flag) +
        ", text='" + text + '\'' +
        ", source='" + (sourceTwitter == null ? "null" : sourceTwitter.getTid()) + '\'' +
        '}';
	}

	@Override
	public int compareTo(Mentions o) {
		// TODO Auto-generated method stub
		if(this == o)
			return 0;
		return Long.valueOf(this.createTime).compareTo(o.getCreateTime());
	}


	public String getProvider() {
		return provider;
	}
	public void setProvider(String provider) {
		this.provider = provider;
	}
	public String getTid() {
		return tid;
	}
	public void setTid(String id) {
		this.tid = id;
	}
	public String getNick() {
		return nick;
	}
	public void setNick(String nick) {
		this.nick = nick;
	}
	public String getUid() {
		return uid;
	}
	public void setUid(String uid) {
		this.uid = uid;
	}
	public String getText() {
		return text;
	}
	public void setText(String text) {
		this.text = text;
	}
	public long getCreateTime() {
		return createTime;
	}
	public void setCreateTime(long createTime) {
		this.createTime = createTime;
	}
	public long getActionId() {
		return actionId;
	}
	public void setActionId(long actionId) {
		this.actionId = actionId;
	}
	public Mentions getSourceTwitter() {
		return sourceTwitter;
	}
	public void setSourceTwitter(Mentions sourceTwitter) {
		this.sourceTwitter = sourceTwitter;
	}
	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	public Short getType() {
		return type;
	}
	public void setType(Short type) {
		this.type = type;
	}
	public long getSystemTime() {
		return systemTime;
	}
	public void setSystemTime(long systemTime) {
		this.systemTime = systemTime;
	}
	public MyHttpClient getHttpClient() {
		return httpClient;
	}
	public void setHttpClient(MyHttpClient httpClient) {
		this.httpClient = httpClient;
	}
	public Short getFlag() {
		return flag;
	}
	public void setFlag(Short flag) {
		this.flag = flag;
	}
	public String getReply() {
		return reply;
	}
	public void setReply(String reply) {
		this.reply = reply;
	}
	public RobotGang getRobotGang() {
		return robotGang;
	}
	public void setRobotGang(RobotGang robotGang) {
		this.robotGang = robotGang;
	}
}
